package com.ycb.utils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 黄泽群
 * @since 2023-12-19
 */
public class TCCUtil {

    private static Map<String,Map<String,Object>> TCC_MAP = new ConcurrentHashMap<>();

    private static final String FLAG_KEY = "FLAG_KEY";

    public static void setFlag(String xid){
        put(xid,FLAG_KEY,System.currentTimeMillis());
    }

    public static boolean existFlag(String xid){
        Map<String, Object> params = getParams(xid);
        return  params != null && !params.isEmpty() ;
    }

    public static void put(String xid,String key,Object val){
        Map<String, Object> map = TCC_MAP.get(xid);
        if (map == null){
            synchronized (TCCUtil.class){
                map = TCC_MAP.get(xid);
                if (map == null){
                    TCC_MAP.put(xid,new ConcurrentHashMap<>());
                    map = TCC_MAP.get(xid);
                }
            }
        }
        map.put(key,val);
    }

    public static Map<String,Object> getParams(String xid){
        return TCC_MAP.get(xid);
    }

    public static Object getParams(String xid,String key){
        Map<String, Object> map = TCC_MAP.get(xid);
        if (map == null){
            return null;
        }
        return map.get(key);
    }

    public static void remove(String xid){
        TCC_MAP.remove(xid);
    }

}
